﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BT.UI
{
    public class SpriteAnimation
    {

        public int FramesPerSecond { get; private set; }

        public int CurrentFrame { get; private set; }

        public bool Active { get; private set; }

        public Texture2D Texture
        {
            get { return textureList.Texture; }
        }

        public Rectangle SourceRectangle
        {
            get { return textureList.Rectangles[CurrentFrame]; }
        }

        private bool reverse;
        private bool loop;
        private TextureList textureList;
        private TimeSpan elapsed;
        

        public SpriteAnimation(TextureList textureList, int framesPerSecond, bool reverse, bool loop)
        {
            FramesPerSecond = framesPerSecond;
            this.textureList = textureList;
            this.reverse = reverse;
            this.loop = loop;

            if (reverse)
                CurrentFrame = textureList.FrameCount - 1;
        }

        public void Update(GameTime gameTime)
        {
            if (!Active)
                return;

            elapsed += gameTime.ElapsedGameTime;

            if (elapsed.TotalSeconds < 1f / FramesPerSecond)
                return;

            elapsed = TimeSpan.FromSeconds(0);

            if (reverse)
            {
                CurrentFrame--;

                if (CurrentFrame == -1)
                    CurrentFrame = textureList.FrameCount - 1;
                
                Active = loop || (CurrentFrame != 0);
            }
            else
            {
                CurrentFrame = (CurrentFrame + 1) % textureList.FrameCount;
                Active = loop || (CurrentFrame != textureList.FrameCount - 1);
            }
        }

        public void Start()
        {
            Active = true;
        }

        public void Stop()
        {
            Active = false;
        }

    }
}
